<?php
include_once('config/config.php');


if ($_POST) {
  $params = $_POST;
  $action = $_POST['action'];
  if($action == 'checkName'){
    $name = $_POST['name'];
    if(empty(trim($name))){
      error('部门不能为空');
    }
    $depId = dbFind("SELECT `id` FROM `department` WHERE `name` = '$name'");
    if ($depId) {
      error('部门已经存在');
    } else {
      success('部门可以使用');
    }
  }
  //封装数组
  $data = [
    'name' => $params['name']
  ];

  //新增新数据到数据库
  $res = dbAdd('department', $data);
  if ($res) {
    ShowMsg('新增成功',"departmentList.php");
    exit;
  } else {
    ShowMsg('新增失败');
    exit;
  }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
  <title>部门</title>
  <!-- 引用公共头部 -->
  <?php include_once('common/meta.php'); ?>

  <style>
    .icon-list {
      margin-right: 5px;
    }
  </style>
</head>

<body>

  <!-- 引用公共头部 -->
  <?php include_once('common/header.php'); ?>

  <!-- 引用侧边菜单 -->
  <?php include_once('common/sidebar.php'); ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">新增部门</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="index.php">首页</a> <span class="divider">/</span></li>
      <li class="active">部门</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">

        <div class="btn-toolbar">
          <button class="btn btn-primary " onClick="location='departmentList.php'"><i class="icon-list"></i>部门</button>
          <div class="btn-group">
          </div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form method="POST" enctype="multipart/form-data">
                <label>部门名称</label>
                <input type="text" value="" class="input-xxlarge" name="name" placeholder="请输入部门名称" required>
                <span id="name" style="margin-left: 10px;"></span>
                <br />
                <input class="btn btn-primary btn-submit" type="submit" value="提交" />
              </form>
            </div>
          </div>
        </div>

        <!-- 引用公共底部 -->
        <?php include_once('common/footer.php'); ?>

      </div>
    </div>
  </div>
</body>

</html>
<!-- 引用script -->
<?php include_once('common/script.php'); ?>

<script>
  $('.input-xxlarge').change(function() {
    let name = $('.input-xxlarge').val();

    $.ajax({
      type: 'post',
      url: 'departmentAdd.php',
      data: {
        name,
        action: 'checkName'
      },
      dataType: 'json',
      success: function(res) {
        if (res.code === 1) {
          $('#name').html(res.msg).css({"color":"green"})
        } else {
          $('#name').html(res.msg).css({"color":"red"})
        }
      },
      // 请求失败的回调函数 404 301 500等
      error: function(error) {
        console.log(error)
      }
    })
  });
</script>